from django.shortcuts import render

# Create your views here.
# _*_ coding=utf-8 _*_
__author__ = "SRF"
__date__ = "2020/5/12 11:58"
import pymysql
import json
from django.http import HttpResponse
from scan.component.ipTraverse import *
from scan.component import geo
import nmap


def DLdata(request):
    page = int(request.GET.get("page"))
    result = getDL(page)
    return HttpResponse(json.dumps(result))


def getDL(page):  # start从1计
    d = {
        "page_nums": 0,
        "type": "FeatureCollection",
        "features": [
            {
                "type": "Feature",
                "geometry": {
                    "type": "Polygon",
                    "coordinates": [

                    ]
                },
                "properties": {
                    "name": "纳米比亚",
                    "name_en": "NAMIBIA",
                    "code": "NAM",
                    "centroid": [
                        17.45286813207547,
                        -22.074524419811336
                    ]
                }
            }
        ]
    }
    conn = pymysql.connect(host="47.94.151.63", port=3306, user="contest", passwd="1327764786", db="contest_data",
                           charset="utf8")  # 这里写上面设置的密码

    cursor = conn.cursor()
    sql = """select count(*) from devices_location"""
    cursor.execute(sql)
    num = cursor.fetchone()[0]
    d["page_nums"] = num // 50 + 1
    start = (page - 1) * 50
    limit = 50

    sql = "select lat,lon from devices_location limit {0},{1}".format(start, min(limit, num - start + 1))
    cursor.execute(sql)
    res = cursor.fetchall()
    d["features"][0]["geometry"]["coordinates"] = res
    cursor.close()
    conn.close()
    return json.loads(json.dumps(d))


'''  
request method:get
url:127.0.0.1:8000/DLdata?page=1
return data:
{"page_nums": 22105, "type": "FeatureCollection", "features": [{"type": "Feature", "geometry": {"type": "Polygon", "coordinates": [["21.7866", "82.794762"], ["36.448151", "127.850166"], ["39.89489", "-2.98831"], ["6.47279", "-66.589043"], ["32.824552", "-117.0951632"], ["36.204824", "138.252924"], ["62.198448", "17.55142"], ["23.62574", "-101.956253"], ["40.818311", "111.670801"], ["50.688438", "3.18125"], ["15.4603", "18.73877"], ["6.47279", "-66.589043"], ["8.4177", "-80.112778"], ["46.542511", "24.55344"], ["39.89489", "-2.98831"], ["6.47279", "-66.589043"], ["46.813202", "8.22395"], ["42.4974694", "-94.1680158"], ["36.778261", "-119.4179324"], ["8.4177", "-80.112778"], ["36.448151", "127.850166"], ["44.9591352", "-89.6301221"], ["32.824552", "-117.0951632"], ["24.299112", "116.117582"], ["46.860802", "103.836807"], ["36.171909", "-115.139969"], ["53.3547792", "83.7697833"], ["29.31015", "47.49445"], ["49.803879", "15.47491"], ["54.606331", "39.71648"], ["30.441851", "69.359703"], ["51.164181", "10.45415"], ["33.3806716", "-84.7996573"], ["62.198448", "17.55142"], ["44.3148443", "-85.6023643"], ["0.10974", "113.917397"], ["15.9742", "107.867996"], ["42.503819", "12.57347"], ["39.9525839", "-75.1652215"], ["41.4565393", "-72.8803058"], ["55.741638", "37.605061"], ["38.823502", "-75.923813"], ["56.954681", "-98.308968"], ["22.396428", "114.109497"], ["52.0515032", "113.4711906"], ["46.71067", "1.71819"], ["53.7872611", "-68.4339115"], ["42.503819", "12.57347"], ["46.71067", "1.71819"], ["33.9732275", "-78.3858371"]]}, "properties": {"name": "\u7eb3\u7c73\u6bd4\u4e9a", "name_en": "NAMIBIA", "code": "NAM", "centroid": [17.45286813207547, -22.074524419811336]}}]}

'''


def getCoordinates_client(request):
    startIP = request.POST.get("startIP", "")
    endIP = request.POST.get("endIP", "")
    startIPL = startIP.split(".")
    endIPL = endIP.split('.')
    d = {
        "type": "FeatureCollection",
        "crs": {
            "type": "name",
            "properties": {
                "name": "urn:ogc:def:crs:OGC:1.3:CRS84"
            }
        },
        "features": [

            {
                "type": "Feature",
                "geometry": {
                    "type": "Polygon",
                    "coordinates": [

                    ]
                },
                "properties": {
                    "name": "列支敦士登",
                    "name_en": "Liechtenstein",
                    "id": "LIE"
                }
            }
        ],
        "client": {
            "ip": "",  # 客户端ip
            "coordinate": []  # 客户端经纬度
        },
        "ipList": [],  # 存活主机ip列表
    }

    ip_lists = [int2ip(x) for x in range(ip2int(startIP), ip2int(endIP) + 1)]
    nmScan, temp_ip_lists = nmap.PortScanner(), []
    hosts = ""
    for count in range(4):
        hosts += startIPL[count] + "-" + endIPL[count] + '.'
    hosts = hosts.rstrip('.')
    print(hosts)
    ret = nmScan.scan(hosts=hosts, arguments='-sP')
    print('扫描时间：' + ret['nmap']['scanstats']['timestr'] + '\n命令参数:' + ret['nmap']['command_line'])
    for ip in ip_lists[:]:
        print('ip地址：' + ip + '：')
        if ip not in ret['scan']:
            temp_ip_lists.append(ip)
            print('扫描超时')
            ip_lists.remove(ip)
        else:
            print('已扫描到主机，主机名：' + ret['scan'][ip]['hostnames'][0]['name'])

    coordinate = []

    for i in ip_lists:
        coordinate.append(geo.getCoordinate(i))
    d["features"][0]["geometry"]["coordinates"] = coordinate
    if 'HTTP_X_FORWARDED_FOR' in request.META:
        clientIP = request.META['HTTP_X_FORWARDED_FOR']
    else:
        clientIP = request.META['REMOTE_ADDR']
    print(clientIP)
    d["client"]["ip"] = clientIP
    d["client"]["coordinate"] = geo.getCoordinate(clientIP)
    d["ipList"] = ip_lists
    return d, ip_lists


def getWorld(request):
    if not request.POST:
        d = getDL(1)

        for i in range(2, 21):
            d["features"][0]["geometry"]["coordinates"].extend(
                getDL(i)["features"][0]["geometry"]["coordinates"])
    else:
        d = getCoordinates_client(request)[0]
    print(d)
    return HttpResponse(json.dumps(d))


def getLine(request):
    if not request.POST:
        d = getDL(1)  # 50条数据
        print(d)

        # for i in range(2, 21):
        #     d["features"][0]["geometry"]["coordinates"].extend(
        #         getDL(i)["features"][0]["geometry"]["coordinates"])
    else:
        d, ip_list = getCoordinates_client(request)
        d["from_to"] = []
        d["listInfo"] = []
        client_coor = d["client"]["coordinate"]
        conn = pymysql.connect(host="47.94.151.63", port=3306, user="contest", passwd="1327764786", db="contest_data",
                               charset="utf8", cursorclass=pymysql.cursors.DictCursor)

        cursor = conn.cursor()
        d1 = {
            "ip": "",
            "port": "",
            "country": "",
            "deviceBrand": "",
            "listInfo": []
        }
        i = 0
        for ip in ip_list:

            sql = """select device_id,ip,port,country from devices_location where ip='%s' """ % (ip)
            cursor.execute(sql)
            target_coor = d["features"][0]["geometry"]["coordinates"][i]
            print(client_coor)
            print(client_coor == [None, None])
            from_to = {"from": "" if client_coor == [None, None]
            else ",".join(map(str, client_coor)), "to": "" if target_coor == [None, None]
            else ",".join(map(str, target_coor))}
            d["from_to"].append(from_to)

            if cursor.fetchone() is not None:
                d1.update(cursor.fetchone())
                device_id = d1['device_id']
                sql = "select deviceBrand from devices where device_id= '%s' " % (device_id)
                cursor.execute(sql)
                d2 = cursor.fetchone()
                d1.update(d2)
            d["listInfo"].append(d1)
            i += 1

        cursor.close()
        conn.close()
    print(d)

    return HttpResponse(json.dumps(d))
